package com.example.home7;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class ExternalStorage extends Fragment {
    public ExternalStorage() {
        super(R.layout.external);
    }
    private final String FILE_NAME = "External.txt";
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getView().findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter bw = new BufferedWriter(
                            new OutputStreamWriter(
                            new FileOutputStream(
                                    new File(getActivity().getExternalFilesDir(null), FILE_NAME))));
                    bw.write("hellowrold");
                    bw.close();
                    Toast.makeText(getActivity(), "外部写入", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        getView().findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(
                                    new FileInputStream(
                                            new File(getActivity().getExternalFilesDir(null), FILE_NAME)
                                    )
                            )
                    );
                    Toast.makeText(getActivity(),br.readLine(), Toast.LENGTH_SHORT).show();
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
